import React from 'react';
import {
    Row,
    Col,
    Table,
    Icon,
    Button,
    Modal,
    notification,
    Form,
    Tooltip,
    Switch,
    AutoComplete,
    Popconfirm,
} from 'antd';
import axios from 'axios';
import intercept from '../../../utils/intercept';
import { config } from 'utils';
import { Input } from 'antd';
import '../less/common.less';
const Search = Input.Search;
const FormItem = Form.Item;
const Option = AutoComplete.Option;

class CustomBusLineStartTimeClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            loading: false,
            pagination: {
                current: 1,
                pagesize: 10
            },
            onChange: this.onChange,
            formTitle: '',
            formVisible: false,
            isLinkStation: false,
            isEnable: false,
            userOrgans: [],
            organNameValid: '',
            isDisplay: 'none',
            busLineId:-1,
        }
    };

    componentDidMount() {
        this.getBusLineStartTime()
        this.getUserOrgans()
    };

    openNotification = (title, desc, color) => {
        notification.open({
            message: title,
            description: desc,
            icon: <Icon type="smile-circle" style={{ color: color }} />,
        });
    };

    onChange = (pagination, filters, sorter) => {
        this.getBusLineStartTime({
            sortField: sorter.field,
            sortOrder: sorter.order,
            page: pagination.current,
            ...filters
        });
    };

    getBusLineStartTime = (params = {}) => {
        const token = sessionStorage.getItem("token");
        this.setState({ loading: true,busLineId:this.props.location.query.busLineId,});
        axios
            .get(`${config.api}CustomLine/GetBusLineStartTime?Page=${params.page}&&PageSize=${this.state.pagination.pageSize}&&busLineId=${this.props.location.query.busLineId}`, { headers: { Authorization: 'Bearer ' + token } })
            .then((data) => {
                const pagination = {
                    ...this.state.pagination
                };
                pagination.total = data.data.pageList.totalRows;
                pagination.current = params.page;
                this.setState({ loading: false, dataSource: data.data.pageList.collections, pagination });
            })
            .catch(err => {
                intercept;
            });
    }

    StartTimeForm = (ev, record) => {
        this.props.form
            .setFieldsValue({
                key: record.key,
                busStartTime: record.busStartTime,
                busNumber: record.busNumber,
                stationName: record.stationName,
                targetCode: record.targetCode,
            });
        this.setState({
            formVisible: true,
            isLinkStation: record.isLinkStation,
            isEnable: record.isEnable,
            formTitle: '编辑发车配置',
            isDisplay: record.isLinkStation ? 'block' : 'none',
        });
    }

    handleCancel = () => {
        this.setState({
            formVisible: false,
            organNameValid: '',
        })
    }

    handleReset = () => {
        this
            .props
            .form
            .resetFields();
        this.setState({
            organNameValid: '',
        })
    }

    addBusTimeForm = () => {
        this.handleReset();
        this.setState({
            formVisible: true,
            isEnable: false,
            isLinkStation: false,
            formTitle: '新增发车时间'
        });
        this.props.form
            .setFieldsValue({
                key: -1,
                busStartTime:'',
            });
    }

    getUserOrgans = () => {
        const token = sessionStorage.getItem("token");
        axios
            .get(`${config.api}User/GetOrgansKey`, {
                headers: {
                    Authorization: 'Bearer ' + token
                }
            })
            .then((res) => {
                let tmp = res
                    .data
                    .userOrgans
                    .map(m => (
                        <Option key={m.key} value={m.label}>
                            {m.label}
                        </Option>
                    ));

                let all = res
                    .data
                    .allOrgans
                    .map(m => (
                        <Option key={m.key} value={m.label}>
                            {m.label}
                        </Option>
                    ));
                this.setState({ userOrgans: tmp, allOrgans: all });
            })
            .catch(err => {
                intercept;
            });
    }

    organNameValid = (rule, value, callback) => {
        let tem = this.state.userOrgans.filter(m => m.props.value == value);
        if (tem.length > 0) {
            this.setState({
                organNameValid: 'success',
            })
        }
        else {
            this.setState({
                organNameValid: 'error',
            })
        }

        callback();
    }

    SwitchChangeForm = (checked, type) => {
        //是否关联车站
        if (type == 1) {
            this.setState({
                isLinkStation: !checked,
                isDisplay: checked ? 'none' : 'block',
            });
        }
        //是否启用
        else {
            this.setState({
                isEnable: !checked,
            });
        }
    }

    editIsEnableOrLink = (checked, record, type) => {
        this.setState({ loading: true });
        const token = sessionStorage.getItem("token");
        let dataSource = this.state.dataSource;
        let editType = 3;
        if (type == 1)
        {
            editType = 4;
            for (let i = 0; i < dataSource.length; i++) {
                if (dataSource[i].key == record.key) {
                    dataSource[i].isLinkStation = checked;
                }
            }
        }
        else
        {
            for (let i = 0; i < dataSource.length; i++) {
                if (dataSource[i].key == record.key) {
                    dataSource[i].isEnable = checked;
                }
            }
        }
        axios
            .post(`${config.api}CustomLine/EditBusLineStartTime`, { editType: editType, isChecked: checked, BusLineID: record.busLineId, key: record.key }, { headers: { Authorization: 'Bearer ' + token } })
            .then((data) => {
                if (data.data.result) {
                    this.openNotification("状态修改", checked ? "开启成功" : "关闭成功", "#108ee9");
                }
                else {
                    this.openNotification("状态修改", data.data.errorMessage, "red");
                    if (type == 1)
                    {
                        for (let i = 0; i < dataSource.length; i++) {
                            if (dataSource[i].key == record.key) {
                                dataSource[i].isLinkStation = !checked;
                            }
                        }
                    }
                    else
                    {
                        for (let i = 0; i < dataSource.length; i++) {
                            if (dataSource[i].key == record.key) {
                                dataSource[i].isEnable = !checked;
                            }
                        }
                    }
                }
                this.setState({ loading: false });
            })
            .catch(err => {
                intercept;
            });
        this.setState({
            dataSource
        })
        
    }

    deleteStartTime=(record)=>{
        this.setState({ loading: true });
        const token = sessionStorage.getItem("token");
        let postdata = {
            busLineId:record.busLineId,
            key:record.key,
            editType:5,
        }
        axios
        .post(`${config.api}CustomLine/EditBusLineStartTime`, postdata, {
            headers: {
                Authorization: 'Bearer ' + token
            }
        })
        .then((data) => {
            if (data.data.result) {
                this.setState({ formVisible: false });
                this.handleReset();
                let dataSource = this.state.dataSource;
                let index=-1;
                for (let i = 0; i < dataSource.length; i++) {
                    if (dataSource[i].key == record.key) {
                        index=i;
                    }
                }
                dataSource.splice(index,1);
                this.setState({
                    dataSource,
                });
                this.openNotification("删除发车时间", "删除成功", "#108ee9");
            } else {
                this.openNotification("删除发车时间", data.data.errorMessage, "red");
            }
            this.setState({ loading: false });
        }).catch(err => {
            intercept;
        });
    }

    editStartTime=(e)=>{
        e.preventDefault();
        this
        .props
        .form
        .validateFieldsAndScroll((err, values) => {
            if (!err) {
                this.setState({ loading: true });
                const token = sessionStorage.getItem("token");
                let postdata = {
                    busLineId:this.state.busLineId,
                    key:values.key,
                    busStartTime:values.busStartTime,
                    busNumber:values.busNumber,
                    stationName:values.stationName,
                    targetCode:values.targetCode,
                    isEnable:this.state.isEnable,
                    isLinkStation:this.state.isLinkStation,
                    editType:values.key<=0 ? 1:2,
                }
                axios
                    .post(`${config.api}CustomLine/EditBusLineStartTime`, postdata, {
                        headers: {
                            Authorization: 'Bearer ' + token
                        }
                    })
                    .then((data) => {
                        if (data.data.result) {
                            //this.openNotification("编辑线路", "修改线路信息成功", "#108ee9");
                            this.setState({ formVisible: false });
                            this
                                .props
                                .form
                                .resetFields();

                            let dataSource = this.state.dataSource;
                            let response = dataSource.filter(m => m.key == data.data.startTimeConfig.key);
                            //新增
                            if (response.length <= 0) {
                                dataSource.unshift(data.data.startTimeConfig);
                                this.openNotification("新增成功", "添加发车时间成功", "#108ee9");
                            }
                            //编辑
                            else {
                                for (let i = 0; i < dataSource.length; i++) {
                                    if (dataSource[i].key == data.data.startTimeConfig.key) {
                                        dataSource[i] = data.data.startTimeConfig;
                                    }
                                }
                                this.openNotification("编辑发车时间", "修改发车时间成功", "#108ee9");
                            }
                            this.setState({
                                dataSource,
                            });
                        } else {
                            this.openNotification("编辑发车时间", data.data.errorMessage, "red");
                        }
                        this.setState({ loading: false });
                    }).catch(err => {
                        intercept;
                    });
            }
        });
    }

    render() {
        const columns = [
            {
                title: '发车时间',
                dataIndex: 'busStartTime',
                width: 100
            },
            {
                title: '始发站',
                dataIndex: 'stationName',
                width: 100
            },
            {
                title: '是否关联站内',
                dataIndex: 'isLinkStation',
                width: 100,
                render: (text, record) => {
                    return (<Switch
                        checkedChildren="是"
                        unCheckedChildren="否"
                        onChange={(checked, values) => {
                            this.editIsEnableOrLink(checked, record, 1)
                        }}
                        checked={record.isLinkStation}
                    />)
                }
            },
            {
                title: '班次号',
                dataIndex: 'busNumber',
                width: 100
            },
            {
                title: '是否启用',
                dataIndex: 'isEnable',
                width: 100,
                render: (text, record) => {
                    return (<Switch
                        checkedChildren="开"
                        unCheckedChildren="关"
                        onChange={(checked, values) => {
                            this.editIsEnableOrLink(checked, record, 2)
                        }}
                        checked={record.isEnable}
                    />)
                }
            },
            {
                title: '操作',
                key: 'operation',
                width: 100,
                render: (text, record) => {
                    return (
                        <div>
                            <span><Button type="primary" onClick={(ev, data) => { this.StartTimeForm(ev, record) }}>编辑</Button></span>
                            <span style={{ visibility: 'hidden' }}>藏</span>
                            <span>
                                <Popconfirm placement="top" title={"确定要删除吗？"} onConfirm={(data) => this.deleteStartTime(record)} okText="确定" cancelText="取消">
                                    <Button type="danger" ghost>删除</Button>
                                </Popconfirm>
                            </span>
                        </div>
                    )
                }
            },
        ];

        const { getFieldDecorator } = this.props.form;
        const className = "components-table-demo-nested";
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 6
                }
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 14
                }
            }
        };

        return (
            <div>
                <Row gutter={8} style={{
                    //marginTop: '10px'
                }}>
                    <Col span={2}></Col>
                    <Col span={20}>
                        <div
                            style={{
                                textAlign: 'center',
                                margin: 10
                            }}>
                            <Search
                                style={{
                                    width: 600,
                                    visibility: 'hidden'
                                }} />
                            <Button type="primary" style={{ float: 'right' }} onClick={this.addBusTimeForm}>新增</Button>
                        </div>
                        <Table
                            rowKey={record => record.key}
                            {...this.state}
                            bordered={true}
                            className={className}
                            columns={columns}
                            style={{ background: 'white' }}
                        />
                    </Col>
                    <Col span={2}></Col>
                </Row>
                <Modal
                    title={this.state.formTitle}
                    width={500}
                    visible={this.state.formVisible}
                    footer={null}
                    onCancel={this.handleCancel}
                    maskClosable={false}
                >
                    <Form onSubmit={(e, type) => this.editStartTime(e)} className="ant-advanced-search-form">
                        <Row>
                            <FormItem
                                style={{ display: 'none' }}
                                {...formItemLayout}
                                label={(
                                    <span>
                                        主键
                                <Tooltip title="自动填充">
                                            <Icon type="question-circle-o" />
                                        </Tooltip>
                                    </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('key', {
                                    rules: [
                                        {
                                            required: false,
                                        }
                                    ]
                                })(<Input />)}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(<span>
                                    发车时间
                                    <Tooltip title="自动填充">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('busStartTime', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请输入发车时间!',
                                            whitespace: true
                                        }
                                    ]
                                })(<input type="time" />)}
                            </FormItem>

                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        始发站
                                <Tooltip title="自动填充">
                                            <Icon type="question-circle-o" />
                                        </Tooltip>
                                    </span>
                                )}
                                hasFeedback
                                validateStatus={this.state.organNameValid}>
                                {getFieldDecorator('stationName', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择始发站!',
                                        },
                                        {
                                            validator: this.organNameValid,
                                        }
                                    ]
                                })(<AutoComplete
                                    dataSource={this.state.userOrgans}
                                    filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1} />)}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        是否关联车站
                                    <Tooltip title="自动填充">
                                            <Icon type="question-circle-o" />
                                        </Tooltip>
                                    </span>
                                )}
                                hasFeedback>
                                {(<Switch checkedChildren="是"
                                    unCheckedChildren="否"
                                    checked={this.state.isLinkStation}
                                    onChange={(checked, type) => {
                                        this.SwitchChangeForm(this.state.isLinkStation, 1)
                                    }}
                                />)}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        是否启用
                                    <Tooltip title="自动填充">
                                            <Icon type="question-circle-o" />
                                        </Tooltip>
                                    </span>
                                )}
                                hasFeedback>
                                {(<Switch checkedChildren="启用"
                                    unCheckedChildren="禁用"
                                    checked={this.state.isEnable}
                                    onChange={(checked, type) => {
                                        this.SwitchChangeForm(this.state.isEnable, 2)
                                    }}
                                />)}
                            </FormItem>
                            <FormItem
                                style={{ display: this.state.isDisplay }}
                                {...formItemLayout}
                                label={(
                                    <span>
                                        目的地编码
                                    <Tooltip title="自动填充">
                                            <Icon type="question-circle-o" />
                                        </Tooltip>
                                    </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('targetCode', {
                                    rules: [
                                        {
                                            required: this.state.isLinkStation,
                                            message: '请选择终点!',
                                            whitespace: true
                                        }
                                    ]
                                })(<Input />)}
                            </FormItem>
                            <FormItem
                                style={{ display: this.state.isDisplay }}
                                {...formItemLayout}
                                label={(
                                    <span>
                                        站内班次号
                                    <Tooltip title="自动填充">
                                            <Icon type="question-circle-o" />
                                        </Tooltip>
                                    </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('busNumber', {
                                    rules: [
                                        {
                                            required: this.state.isLinkStation,
                                            message: '请选择终点!',
                                            whitespace: true
                                        }
                                    ]
                                })(<Input />)}
                            </FormItem>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <FormItem className="center">
                                    <Button onClick={this.handleReset}>重置</Button>{' '}
                                    <Button type="primary" htmlType="submit">确定</Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>

            </div>
        )
    }
}

const CustomBusLineStartTime = Form.create()(CustomBusLineStartTimeClass);
export default CustomBusLineStartTime
